var gulp = require('gulp');
// 自动同步浏览器插件
var browserSync = require('browser-sync');
// 同步运行任务插件
var runSequence = require('run-sequence');
// html
var htmlmin = require('gulp-htmlmin');
// 编译less
var less = require('gulp-less');
// 给css3属性添加浏览器前缀插件
var autoprefixer = require('gulp-autoprefixer');
// css map
var sourcemaps = require('gulp-sourcemaps');
// 压缩css插件
var cssnano = require('gulp-cssnano');
var cleanCSS = require('gulp-clean-css');
var concat = require('gulp-concat');
// 压缩js
var uglify = require('gulp-uglify');
// 压缩图片
var imagemin = require('gulp-imagemin');
// 压缩日志
var gutil = require('gulp-util');
// 起本地静态资源服务器，及监听
gulp.task('browserSync', () => {
    browserSync({
        server: {
            baseDir: './',
            index: 'index.html'
        }
    });
});
gulp.task('testHtmlmin', ()=> {
    var options = {
        removeComments: true,//清除HTML注释
        collapseWhitespace: true,//压缩HTML
        collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input />
        removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
        removeScriptTypeAttributes: true,//删除<script>的type="text/javascript"
        removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
        minifyJS: true,//压缩页面JS
        minifyCSS: true//压缩页面CSS
    };
    gulp.src('*.html')
        .pipe(htmlmin(options))
        .pipe(gulp.dest('dist'));
});
// 编译less文件,并压缩
gulp.task('less', () =>
    gulp
    .src('static/less/**/**.less')
    .pipe(sourcemaps.init())
    .pipe(less())
    .pipe(sourcemaps.write({ includeContent: false }))
    .pipe(autoprefixer())
    .pipe(sourcemaps.write('/'))
    .pipe(cleanCSS({compatibility: 'ie8'}))
    // .pipe(concat('all.css'))
    .pipe(gulp.dest('static/css'))
);
// 压缩 js 文件
// 在命令行使用 gulp script 启动此任务
gulp.task('script', () => {
    // 1. 找到文件
    gulp.src(['controller/*.js', 'controller/**/*.js', '!controller/module.js'])
    // 2. 压缩文件
    .pipe(uglify())
    // 3. 另存压缩后的文件
    .pipe(gulp.dest('dist'));
});

// gulp-imagemin 图片压缩
gulp.task('image', () => {
    gulp.src('static/images/**/*')
        .pipe(imagemin({ progressive: true }))
        .on('error', gutil.log)
        .pipe(gulp.dest('dist/images'));
});
// 监听文件修改
gulp.task('watch', ['browserSync', 'testHtmlmin', 'less', 'script', 'image'], () => {

    gulp.watch([
        '*.html',
        'views/**/*.html'
    ], browserSync.reload);

    gulp.watch([
        'require.config.js',
        'controller/*.js',
        'controller/**/*.js'
    ], browserSync.reload);

    gulp.watch([
        'static/less/*.less',
        'static/less/**/*.less'
    ], ['less', browserSync.reload]);

    gulp.watch('docs/**/*.md', ['md', browserSync.reload]);
})

// 默认任务
gulp.task('default', (callback) => {
    runSequence(['browserSync', 'watch'], callback);
})